package com.boc.langxiang.ui.activity.me;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.boc.langxiang.App;
import com.boc.langxiang.R;
import com.boc.langxiang.contract.ImageContract;
import com.boc.langxiang.contract.me.LeaveFeedBackAndListContract;
import com.boc.langxiang.entity.request.FeedBackRequest;
import com.boc.langxiang.entity.response.LeaveContentList;
import com.boc.langxiang.presenter.ImagePresenter;
import com.boc.langxiang.presenter.me.LeaveFeedBackPresenter;
import com.boc.langxiang.ui.adapter.me.LeaveToFlowOutRVAdapter;
import com.boc.langxiang.util.KeyBoardUtil;
import com.boc.langxiang.util.T;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.loader.GlideImageLoader;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 留言给一定
 */
public class LeaveToFlowOutActivity extends MeBaseToolBarActivity implements LeaveFeedBackAndListContract.View, SwipeRefreshLayout.OnRefreshListener, ImageContract.View {

    @BindView(R.id.rv_me_leave_flow)
    RecyclerView rvMeLeaveFlow;
    @BindView(R.id.iv_me_leave_ic)
    ImageView ivMeLeaveIc;
    @BindView(R.id.et_me_leave_edit)
    EditText etMeLeaveEdit;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    private int mCurrentPage = 1;
    private LeaveToFlowOutRVAdapter mAdapter;
    private List<LeaveContentList> mList;
    private LeaveFeedBackPresenter mPresenter;
    private int pageSize = 5;
    private boolean isRefresh;
    private boolean isLoadMore;
    private String mEditTextContent;
    private ImagePicker imagePicker;
    private ImageItem mImageItem;
    private boolean mIsOnActivityResult;
    private ImageContract.Presenter mImagePresenter;
    private LeaveContentList mLeaveContent;
    private String mPhotourl;
    private boolean mIsFirstRefresh;
    private boolean mIsUploadPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leave_to_flow_out);
        ButterKnife.bind(this);
        setToolBarTitle("留言");
        mPresenter = new LeaveFeedBackPresenter(this);
        mImagePresenter = new ImagePresenter(this);
        rvMeLeaveFlow.setHasFixedSize(true);
        rvMeLeaveFlow.setLayoutManager(new LinearLayoutManager(mContext));
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
        etMeLeaveEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    KeyBoardUtil.closeKeybord(LeaveToFlowOutActivity.this);
                }
                boolean login = isLogin();
                if (login) {
                    mEditTextContent = etMeLeaveEdit.getText().toString();
                    if (TextUtils.isEmpty(mEditTextContent)) {
                        Toast.makeText(App.getInstance(), "输入不能为空", Toast.LENGTH_SHORT).show();
                        return false;
                    } else {
                        mPresenter.feedback(mEditTextContent, FeedBackRequest.NOT_PHOTO);
                        etMeLeaveEdit.setText("");
                        return true;
                    }
                }
                return false;
            }
        });
        initAdapter();
        rvMeLeaveFlow.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefresh) {
                    return true;
                }
                return false;
            }
        });
        mIsFirstRefresh = true;
        mPresenter.feedbackList(String.valueOf(mCurrentPage));
    }

    @Override
    protected void onStart() {
        super.onStart();
        KeyBoardUtil.closeKeybord(this);
    }

    private void initAdapter() {

        mList = new ArrayList<>();

        mAdapter = new LeaveToFlowOutRVAdapter(mContext, mList);
        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.view_empty, (ViewGroup) rvMeLeaveFlow.getParent(), false);
        mAdapter.setEmptyView(emptyView);
        mAdapter.isFirstOnly(false);
        rvMeLeaveFlow.setAdapter(mAdapter);
    }

/*    @Override
    public void onLoadMoreRequested() {
    if (isRefresh || isLoadMore) {
            return;
        }
        isLoadMore = true;
        mCurrentPage++;
        mPresenter.loadMore(String.valueOf(mCurrentPage));
    }*/

    @Override
    public void showLoading() {
        showProgressDialog();
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        isRefresh = false;
        swipeLayout.setRefreshing(false);
        //   isLoadMore = false;
        //   mAdapter.notifyDataChangedAfterLoadMore(false);
//        Toast.makeText(App.getInstance(), msg, Toast.LENGTH_SHORT).show();
   /*     mIsOnError = true;
        if (mList != null) {
            if (mList.size() == 0) {
                mLastPage = 0;
            } else {
                mLastPage = mCurrentPage;
            }
        }*/
    }

    @Override
    public void setTextContentSuccess() {
        if (mIsUploadPhoto) {
            mIsUploadPhoto = false;
        } else {
            LeaveContentList mLeaveContent = new LeaveContentList();
            mLeaveContent.setAnswer(null);
            mLeaveContent.setContent(mEditTextContent);
            mLeaveContent.setPhotourl(mPhotourl);
            mLeaveContent.setIspic("0");
            mList.add(mLeaveContent);
            mAdapter.notifyDataSetChanged();
            rvMeLeaveFlow.smoothScrollToPosition(mList.size());
        }
    }

    @Override
    public void getFeedbackList(List<LeaveContentList> content, String count) {
        swipeLayout.setRefreshing(false);
        if (content == null) {
            return;
        }
        mCurrentPage++;
        Collections.reverse(content);
        this.mList.addAll(0, content);
        LeaveContentList leaveContentList = mList.get(0);
        mPhotourl = leaveContentList.getPhotourl();
        mAdapter.setNewData(mList);
        isRefresh = false;
        if (mIsFirstRefresh) {
            rvMeLeaveFlow.smoothScrollToPosition(mList.size());
            mIsFirstRefresh = false;
        }
    }

/*
    @Override
    public void getLoadMoreList(List<LeaveContentList> content, String count) {
        if (isFinishing()) {
            return;
        }
        isLoadMore = false;
        if (content == null) {
            return;
        }
        if (content.size() < pageSize) {
            mAdapter.notifyDataChangedAfterLoadMore(content, false);
        } else {
            if (mAdapter.getData().size() + content.size() < Integer.parseInt(count)) {
                mAdapter.notifyDataChangedAfterLoadMore(content, true);
            } else {
                mAdapter.notifyDataChangedAfterLoadMore(content, false);
            }
        }
    }
*/

    @Override
    protected int setToolBarBackgroundColor() {
        return Color.WHITE;
    }

    @Override
    protected int setToolBarBackImg() {
        return R.drawable.icon_me_left;
    }

    @Override
    protected int setToolBarTitleColor() {
        return Color.BLACK;
    }

    @Override
    public void onRefresh() {
        if (isRefresh) {
            return;
        }
        isRefresh = true;
        mPresenter.feedbackList(String.valueOf(mCurrentPage));
    }

    @OnClick(R.id.iv_me_leave_ic)
    public void onClick() {
        imagePick();
    }

    private void imagePick() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(GlideImageLoader.getInstance());
        imagePicker.setShowCamera(true);
        imagePicker.setMultiMode(false);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
        imagePicker.setCrop(true);
        imagePicker.setOutPutX(200);
        imagePicker.setOutPutY(300);
        imagePicker.setFocusWidth(600);
        imagePicker.setFocusHeight(900);
        Intent intent = new Intent(mContext, ImageGridActivity.class);
        startActivityForResult(intent, 99);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 99) {
                ArrayList<ImageItem> tempImages = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                mImageItem = tempImages.get(0);
                LeaveContentList mLeaveContent = new LeaveContentList();
                mLeaveContent.setAnswer(null);
                mLeaveContent.setContent(mImageItem.path);
                mLeaveContent.setIspic("1");
                mLeaveContent.setPhotourl(mPhotourl);
                mLeaveContent.setLocalPic(true);
                mList.add(mLeaveContent);
                mAdapter.notifyDataSetChanged();
                rvMeLeaveFlow.smoothScrollToPosition(mList.size());
                mIsOnActivityResult = true;
            } else {
                T.showShort(mContext, "没有数据");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mIsOnActivityResult) {
            if (mImagePresenter == null) {
                mImagePresenter = new ImagePresenter(this);
            }
            mImagePresenter.uploadFile(mImageItem.path);
            mIsOnActivityResult = false;
        }
    }

    @Override
    public void uploadFileFailed() {
        Toast.makeText(App.getInstance(), "图片上传失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void uploadFileSuccess(String content) {
        if (mPresenter != null) {
            mPresenter.feedback(content, FeedBackRequest.IS_PHOTO);
            mIsUploadPhoto = true;
        }
    }
}
